package com.ruoyi.sl.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.sl.domain.*;
import com.ruoyi.sl.mapper.*;
import com.ruoyi.sl.pojo.SlRworkDateForm;
import com.ruoyi.sl.service.ISlDbinfoService;
import com.ruoyi.sl.service.ISlWagesDayService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.sl.service.ISlRworkService;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;
import static com.ruoyi.common.utils.SecurityUtils.getUsername;

/**
 * 报工单Service业务层处理
 * 
 * @author admin
 * @date 2024-06-06
 */
@Service
public class SlRworkServiceImpl implements ISlRworkService 
{
    @Autowired
    private SlRworkMapper slRworkMapper;
    @Autowired
    private SlRworkRmemberMapper slRworkRmemberMapper;
    @Autowired
    private SlAttendanceMapper slAttendanceMapper;
    @Autowired
    private SlRfworkMapper slRfworkMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private ISlDbinfoService slDbinfoService;

    @Autowired
    private SlOrderMapper slOrderMapper;
    @Autowired
    private SlColourMapper slColourMapper;
    @Autowired
    private SlBreedMapper slBreedMapper;
    @Autowired
    private SlTeamMapper slTeamMapper;
    @Autowired
    private SlWagesDayMapper slWagesDayMapper;



    //获报工单ID和参与人获取参与人的所有报工项
    @Override
    public List<SlRwork> selectSlRworkListByRfworkIdAndMember(Long rfworkId,String memberUser){
        return slRworkMapper.selectSlRworkListByRfworkIdAndMember(rfworkId,memberUser);
    }

    //根据日期获取产量
    @Override
    public List<SlWsProduction> selectProductionByQuery(int year,String strType,Long moduleId,Long workshopId){
        if("module".equals(strType)){
            List<Integer> list= new ArrayList<>();
            list.add(year-2);
            list.add(year-1);
            list.add(year);
            return slRworkMapper.selectProductionByYear(list);
        } else if ("workshop".equals(strType)) {
            return slRworkMapper.selectProductionByModuleId(year,moduleId);
        } else if ("gprocess".equals(strType)) {
            return slRworkMapper.selectProductionByWorkshopId(year,moduleId,workshopId);
        }else {
            return null;
        }
    }

    //查询当前报工单下每道工序的生产量
    @Override
    public List<SlRwork> selectGroupProcessByRfworkId(Long rfworkId){
        return slRworkMapper.selectGroupProcessByRfworkId(rfworkId);
    }

    //最后一次报工部分数据
    @Override
    public SlRwork selectSlRworkByLast(String rworkUser,Date rworkDate){
        return slRworkMapper.selectSlRworkByLast(rworkUser,rworkDate);
    }

    /**
     * 查询报工单
     * 
     * @param rworkId 报工单主键
     * @return 报工单
     */
    @Override
    public SlRwork selectSlRworkByRworkId(Long rworkId)
    {
        SlRwork slRwork = slRworkMapper.selectSlRworkByRworkId(rworkId);

        //将批量鼓号生产转成集合
        List<Map> wtermInfoList = new ArrayList<>();
        String[] arrWtermBatch = slRwork.getWtermBatch().split("::",-1);
        String[] arrActualBatch = slRwork.getActualBatch().split("::",-1);
        for(int i=0;i<arrActualBatch.length;i++){
            Map<String,String> map = new HashMap<>();
            map.put("wtermNum",arrWtermBatch[i]);
            map.put("quantum",arrActualBatch[i]);
            wtermInfoList.add(map);
        }
        slRwork.setWtermInfo(wtermInfoList);
        return slRwork;
    }

    /**
     * 查询报工单列表
     * 
     * @param slRwork 报工单
     * @return 报工单
     */
    @Override
    public List<SlRwork> selectSlRworkList(SlRwork slRwork)
    {
        return slRworkMapper.selectSlRworkList(slRwork);
    }

    /**
     * 根据日期查询当日的报工人列表
     *
     * @param rworkDate 日期
     * @return 报工人集合
     */
    @Override
    public List<SlRwork> selectSlRworkUserListByDate(Date rworkDate){
        return slRworkMapper.selectSlRworkUserListByDate(rworkDate);
    }

    /**
     * 查询指定报工单条件的总金额
     *
     * @param slRwork 报工单条件
     * @return 金额
     */
    @Override
    public BigDecimal selectTotalAmountByRwork(SlRwork slRwork) {
        return slRworkMapper.selectTotalAmountByRwork(slRwork);
    }

    /**
     * 查询指定报工单下所有报工项的总金额
     *
     * @param rfworkId 报工单ID
     * @return 金额
     */
    public BigDecimal selectAllPayByRfworkId(Long rfworkId){
        return slRworkMapper.selectAllPayByRfworkId(rfworkId);
    }

    /**
     * 所有已通过审核的报工单
     *
     * @return 集合
     */
    @Override
    public List<SlRwork> selectAllApprovedSlRworkList(){
        return slRworkMapper.selectAllApprovedSlRworkList();
    }

    /**
     * 所有未提交的报工项
     *
     * @return 集合
     */
    @Override
    public List<SlRwork> selectSlRworkListByNoSubmit(SlRwork slRwork){
        return slRworkMapper.selectSlRworkListByNoSubmit(slRwork);
    }

    /**
     * 根据报工单ID查询所有报工项
     *
     * @return 集合
     */
    @Override
    public List<SlRwork> selectSlRworkListByRfworkId(Long rfworkId){
        return slRworkMapper.selectSlRworkListByRfworkId(rfworkId);
    }


    //根据模块，车间，大工序ID 查询包含这些ID的所有报工单ID
    @Override
    public List<Long> selectGroupRworkByAnyId(SlRwork slRwork){
        return slRworkMapper.selectGroupRworkByAnyId(slRwork);
    }

    @Override
    public List<String> selectOftenUserList(String rworkUser) {
        return slRworkMapper.selectOftenUserList(rworkUser);
    }

    /**
     * 新增报工单
     * 
     * @param slRwork 报工单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertSlRwork(SlRwork slRwork)
    {
        slRwork.setCreateTime(DateUtils.getNowDate());
        slRwork.setRworkUser(getUsername());
        slRwork.setRworkNick(getLoginUser().getUser().getNickName());
        slRwork.setRworkDate(DateUtils.getNowDate());

        //订单编号/品种/颜色，不存在则添加
        if(StringUtils.isNotEmpty(slRwork.getWtermOnumber())){
            if(StringUtils.isNull(slOrderMapper.selectSlOrderByOrderNum(slRwork.getWtermOnumber()))){
                SlOrder slOrder = new SlOrder();
                slOrder.setOrderNum(slRwork.getWtermOnumber());
                slOrder.setStatus("0");
                slOrderMapper.insertSlOrder(slOrder);
            }
        }
        if(StringUtils.isNotEmpty(slRwork.getBreedName())){
            if(StringUtils.isNull(slBreedMapper.selectSlBreedByBreedName(slRwork.getBreedName()))){
                SlBreed slBreed = new SlBreed();
                slBreed.setBreedName(slRwork.getBreedName());
                slBreed.setBreedSort(0);
                slBreed.setStatus("0");
                slBreedMapper.insertSlBreed(slBreed);
            }
        }
        if(StringUtils.isNotEmpty(slRwork.getColourName())){
            if(StringUtils.isNull(slColourMapper.selectSlColourByColourName(slRwork.getColourName()))){
                SlColour slColour = new SlColour();
                slColour.setColourName(slRwork.getColourName());
                slColour.setColourSort(0);
                slColour.setStatus("0");
                slColourMapper.insertSlColour(slColour);
            }
        }
        //实际产量x重复次数
        if(slRwork.getRworkActual() != null){
            slRwork.setRworkRepactual(slRwork.getRworkActual().multiply(BigDecimal.valueOf(slRwork.getRworkRepetitions())));
        }

        //批量鼓号，生产数量
        slRwork = batchWtermInfo(slRwork);

        int rows = slRworkMapper.insertSlRwork(slRwork);
        insertSlRworkRmember(slRwork);

        return rows;
    }

    /**
     * 修改报工单
     * 
     * @param slRwork 报工单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateSlRwork(SlRwork slRwork)
    {
        slRwork.setUpdateTime(DateUtils.getNowDate());

        //实际产量x重复次数
        if(slRwork.getRworkActual() != null){
            slRwork.setRworkRepactual(slRwork.getRworkActual().multiply(BigDecimal.valueOf(slRwork.getRworkRepetitions())));
        }

        //报工单提交前编辑报工项
        if(null == slRwork.getRfworkId()){
            //批量鼓号，生产数量
            slRwork = batchWtermInfo(slRwork);
        }else{
            SlRfwork slRfwork = slRfworkMapper.selectSlRfworkByRfworkId(slRwork.getRfworkId());
            //1修改人是报工人，重新审批审核
            if(slRwork.getRworkUser().equals(getLoginUser().getUsername())){
                //删除所有待办
                slDbinfoService.deleteSlDbinfoByRfworkId(slRwork.getRfworkId(),"jjbg");
                //删除工资记录
                slWagesDayMapper.deleteSlWagesDayByRfworkId(slRwork.getRfworkId());
                //给领导创建待办
                createDbInfo(slRwork,slRfwork);
                //修改报工单审批状态
                slRfwork.setLeaderPass("1");
                slRfwork.setLeaderDate(null);
                slRfwork.setRecheckPass("1");
                slRfwork.setRecheckDate(null);
                slRfwork.setIsStatistics("1");
                slRfworkMapper.updateSlRfworkSetData(slRfwork);
            }
        }

        slRworkMapper.deleteSlRworkRmemberByRworkId(slRwork.getRworkId());
        //slRworkRmemberMapper.deleteSlRworkRmemberByRworkId(slRwork.getRworkId());
        insertSlRworkRmember(slRwork);

        return slRworkMapper.updateSlRwork(slRwork);
    }


    /**
     * 修改报工单时间
     *
     * @param slRwork 报工单
     * @return 结果
     */
    @Override
    public int updateSlRworkDateTime(SlRwork slRwork)
    {
        slRwork.setUpdateTime(DateUtils.getNowDate());
        return slRworkMapper.updateSlRwork(slRwork);
    }
    /**
     * 批量删除报工单
     * 
     * @param rworkIds 需要删除的报工单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSlRworkByRworkIds(Long[] rworkIds)
    {
        slRworkMapper.deleteSlRworkRmemberByRworkIds(rworkIds);

        return slRworkMapper.deleteSlRworkByRworkIds(rworkIds);
    }

    /**
     * 删除报工单信息
     * 
     * @param rworkId 报工单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSlRworkByRworkId(Long rworkId)
    {

        slRworkMapper.deleteSlRworkRmemberByRworkId(rworkId);
        return slRworkMapper.deleteSlRworkByRworkId(rworkId);
    }

    /**
     * 将报工单的审核标记改为3，已计算工资
     *
     * @param rworkId 报工单ID
     * @return 结果
     */
    @Override
    public int updateSlRworkToOver(Long rworkId){
        return slRworkMapper.updateSlRworkToOver(rworkId);
    }

    /**
     * 新增操作人信息
     *
     * @param slRwork 报工单对象
     */
    public void insertSlRworkRmember(SlRwork slRwork)
    {
        List<SlRworkRmember> slRworkRmemberList = slRwork.getSlRworkRmemberList();
        Long rworkId = slRwork.getRworkId();
        if (StringUtils.isNotNull(slRworkRmemberList))
        {
            List<SlRworkRmember> list = new ArrayList<SlRworkRmember>();
            for (SlRworkRmember slRworkRmember : slRworkRmemberList)
            {
                slRworkRmember.setRworkId(rworkId);
                slRworkRmember.setRworkDate(slRwork.getRworkDate());
                slRworkRmember.setRworkUser(slRwork.getRworkUser());
                slRworkRmember.setRfworkId(slRwork.getRfworkId());
                list.add(slRworkRmember);
            }
            if (list.size() > 0)
            {
                slRworkMapper.batchSlRworkRmember(list);
            }
        }
    }

    //将数组转字符串存储
    public SlRwork batchWtermInfo(SlRwork slRwork){

        List<Map> wtermInfoList = slRwork.getWtermInfo();
        String wtermBatch = "";
        String actualBatch = "";
        for (int i = 0; i < wtermInfoList.size() ; i++) {
            Map<String,Object> wtermInfo = wtermInfoList.get(i);
            if (i==0){
                wtermBatch =  wtermInfo.get("wtermNum").toString();
                actualBatch = wtermInfo.get("quantum").toString();
            }else {
                wtermBatch = wtermBatch + "::"+wtermInfo.get("wtermNum").toString();
                actualBatch = actualBatch + "::"+wtermInfo.get("quantum").toString();
            }
        }

        slRwork.setWtermBatch(wtermBatch);
        slRwork.setActualBatch(actualBatch);

        return slRwork;
    }



    /**
     * 创建一个报工单关联所有报工项
     *
     * @param slRworkDateForm 报工单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertDateRworks(SlRworkDateForm slRworkDateForm){

        List<SlRwork> rworklist = slRworkDateForm.getRworks();
        SlRwork slRwork = rworklist.get(0);
        SysUser user = userMapper.selectUserByUserName(slRwork.getRworkUser());
        SysUser userLeader = userMapper.selectUserByUserName(slRwork.getLeaderUser());
        //创建工作单
        SlRfwork slRfwork = new SlRfwork();
        slRfwork.setRfworkDate(slRwork.getRworkDate()); //报工日期设为第一个报工项的日期
        slRfwork.setRfworkUser(slRwork.getRworkUser());
        slRfwork.setRfworkNick(user.getNickName());
        slRfwork.setLeaderUser(userLeader.getUserName());
        slRfwork.setLeaderNick(userLeader.getNickName());
        slRfwork.setModuleId(slRwork.getModuleId());
        //slRfwork.setWorkshopId(slTeam.getWorkshopId());
        //slRfwork.setGprocessId(slTeam.getGprocessId());
        slRfwork.setIsNew("0");
        slRfwork.setLeaderPass("1");
        //slRfwork.setRecheckUser()); //复核人
        //slRfwork.setRecheckNick();    //复核人昵称
        slRfwork.setRecheckPass("1");
        slRfwork.setRfwordType("0");    //计件报工
        slRfworkMapper.insertSlRfwork(slRfwork);
        //更新工作项

        Iterator<SlRwork> iterator = rworklist.iterator();
        while(iterator.hasNext()){
            SlRwork rwork = slRworkMapper.selectSlRworkByRworkId(iterator.next().getRworkId());
            Long delRworkId = rwork.getRworkId();
            //拆分批量鼓号分别创建报工项
            String[] arrWtermBatch = rwork.getWtermBatch().split("::",-1);
            String[] arrActualBatch = rwork.getActualBatch().split("::",-1);
            for (int i=0;i<arrActualBatch.length;i++) {
                rwork.setWtermDnumber(arrWtermBatch[i]);
                BigDecimal tmpQuantum = new BigDecimal(arrActualBatch[i]);
                rwork.setRworkActual(tmpQuantum);
                rwork.setRworkRepactual(tmpQuantum.multiply(BigDecimal.valueOf(rwork.getRworkRepetitions())));
                rwork.setEstimatePay(rwork.getProcessPay().multiply(tmpQuantum).multiply(BigDecimal.valueOf(rwork.getRworkRepetitions())));
                rwork.setRfworkId(slRfwork.getRfworkId());
                rwork.setRworkId(null);
                slRworkMapper.insertSlRwork(rwork);
                for (SlRworkRmember slRworkRmember : rwork.getSlRworkRmemberList())
                {
                    slRworkRmember.setRmemberId(null);
                }
                insertSlRworkRmember(rwork);
            }

            deleteSlRworkByRworkId(delRworkId);

        }

        //创建出勤天数
        List<SlAttendance> slAttendanceList = slRworkDateForm.getAttendances();
        for (SlAttendance attendance:slAttendanceList) {
            SysUser attUser = userMapper.selectUserByUserName(attendance.getUserName());
            attendance.setRfworkId(slRfwork.getRfworkId());
            attendance.setLevelId(attUser.getLevelId());
            attendance.setSsmId(attUser.getSsmId());
            attendance.setIsFormalworker(attUser.getIsFormalworker());
            attendance.setIsHourlyworker(attUser.getIsHourlyworker());
            attendance.setRworkDate(slRfwork.getRfworkDate());

            slAttendanceMapper.insertSlAttendance(attendance);
        }

        //给领导创建待办
        createDbInfo(slRwork,slRfwork);

        return 1;
    }

    public void createDbInfo(SlRwork slRwork,SlRfwork slRfwork){
        //给领导创建待办
        SysUser sysUser = userMapper.selectUserByUserName(slRwork.getRworkUser());
        SysUser leaderUser = userMapper.selectUserByUserName(slRwork.getLeaderUser());
        SlDbinfo slDbinfo = new SlDbinfo();
        slDbinfo.setDbLevel(String.valueOf(2));
        slDbinfo.setDbSubject(DateUtils.getDate()+"["+sysUser.getNickName()+"]的计件报工单");
        slDbinfo.setIsDb("0");  //待办
        slDbinfo.setReceptionTime(DateUtils.getNowDate()); //接收时间
        slDbinfo.setPresenterNick(sysUser.getNickName());    //提交人名称
        slDbinfo.setPresenterUser(sysUser.getUserName());    //提交人ID
        slDbinfo.setTransactorsNick(leaderUser.getNickName());  //处理人名
        slDbinfo.setTransactorsUser(leaderUser.getUserName());  //处理人ID
        slDbinfo.setIsDone("3");   //状态
        slDbinfo.setSourceId(slRfwork.getRfworkId());
        slDbinfo.setSource("jjbg");   //计件报工
        slDbinfo.setRwUser(slRwork.getRworkUser());
        slDbinfo.setRwDate(slRwork.getRworkDate());
        slDbinfoService.insertSlDbinfo(slDbinfo);
    }

}
